﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Auction_Intranet.Models;
using Auction_Intranet.Helpers;
using AuctionDataLayer;
using System.DirectoryServices;


namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class ParentController : Controller
    {
        DataRepository m_rep = new DataRepository();

        protected override void OnException(ExceptionContext fc)
        {
            base.OnException(fc);
            Exception ex = fc.Exception;
            Logger.Instance.LogException(ex);            
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            var user = m_rep.GetUserByUsername(username);
            //Create new user in database and add credit(First time)
            if (user == null)
            {
                //System.Diagnostics.Trace.WriteLine("User does not exists in database");
                User newUser = m_rep.getOrCreateRUUserByUserName(username);
                //newUser.Username = username;
                //newUser.Balance = 500;
                m_rep.AddNewUserForAuction(newUser);
                
                //Create a group for this user only  
                Group group = new Group();
                group.Created = DateTime.Now;
                group.Name = username;
                group.Balance = newUser.Balance;
                m_rep.CreateNewSingleGroup(group);

                //Add him to his group 
                UserInGroup userInGroup = new UserInGroup();
                userInGroup.UserId = newUser.Id;
                userInGroup.GroupId = group.Id;
                userInGroup.CreditAdded = newUser.Balance;
                userInGroup.ActiveMember = true;
                m_rep.AddMemberToSingleGroup(userInGroup);

                m_rep.UpdadeUserSingleGroupId(newUser.Id, group.Id);
            }                
        }
    }
}